<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-100 via-gray-100 to-pink-100">
    <div class="container mx-auto px-4 py-8">
      <h1 class="text-3xl font-extrabold text-center mb-6 text-transparent bg-clip-text bg-gradient-to-r from-blue-500 to-pink-500">
        批量模拟测试
      </h1>
      
      <!-- 模拟参数设置 -->
      <div class="bg-white rounded-xl shadow-md p-6 mb-6">
        <h2 class="text-xl font-bold text-gray-800 mb-4">模拟参数</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <div class="mb-4">
              <div class="flex items-center mb-1">
                <label class="block text-sm font-medium text-gray-700 w-24">策略名称</label>
                <input 
                  v-model="simulationParams.strategy_name" 
                  type="text" 
                  class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="输入策略名称"
                >
              </div>
            </div>
            
            <div class="mb-4">
              <div class="flex items-center mb-1">
                <label class="block text-sm font-medium text-gray-700 w-24" for="max-rounds">最大局数</label>
                <div class="flex-1">
                  <input 
                    id="max-rounds" 
                    type="number" 
                    v-model.number="simulationParams.max_rounds"
                    min="10" 
                    max="5000"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                  <p class="mt-1 text-xs text-gray-500">模拟会在牌不足2副（104张）时自动结束，实际局数通常小于此值</p>
                </div>
              </div>
            </div>
            
            <div class="mb-4">
              <div class="flex items-center mb-1">
                <label class="block text-sm font-medium text-gray-700 w-24">随机种子</label>
                <input 
                  v-model.number="simulationParams.deck_seed" 
                  type="number" 
                  class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="留空使用随机种子"
                >
              </div>
            </div>
          </div>
          
          <div>
            <div class="mb-4">
              <div class="flex items-center mb-1">
                <label class="block text-sm font-medium text-gray-700 w-24">观望局数</label>
                <div class="flex-1">
                  <input 
                    v-model.number="simulationParams.parameters.observation_rounds" 
                    type="number" 
                    min="0"
                    max="20"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                  <p class="mt-1 text-xs text-gray-500">开局观望不下注的局数，用于确定主打方向</p>
                </div>
              </div>
            </div>
            
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700 mb-2">选择下注策略表</label>
              <div v-if="loadingStrategyTables" class="flex items-center justify-center py-4">
                <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
                <span class="ml-2 text-sm text-gray-600">加载策略表...</span>
              </div>
              <div v-else class="max-h-60 overflow-y-auto border border-gray-300 rounded-md">
                <div v-if="strategyTables.length === 0" class="p-4 text-center text-gray-500">
                  暂无策略表，请先创建策略表
                </div>
                <div 
                  v-for="table in strategyTables" 
                  :key="table.id"
                  @click="selectStrategyTable(table)"
                  class="p-3 border-b border-gray-200 cursor-pointer hover:bg-gray-50"
                  :class="{'bg-blue-50': selectedStrategyTableId === table.id}"
                >
                  <div class="flex items-center">
                    <input 
                      type="radio" 
                      :id="`strategy-table-${table.id}`"
                      :value="table.id" 
                      v-model="selectedStrategyTableId"
                      class="h-4 w-4 text-blue-600 focus:ring-blue-500"
                    >
                    <label :for="`strategy-table-${table.id}`" class="ml-2 flex-1">
                      <div class="font-medium">{{ table.name }}</div>
                      <div class="text-xs text-gray-500">{{ table.description || '无描述' }}</div>
                      <div class="text-xs text-gray-400 mt-1">{{ table.table_data.length }} 条规则</div>
                    </label>
                    <span v-if="table.is_default" class="px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full">
                      默认
                    </span>
                  </div>
                </div>
              </div>
              <p class="mt-1 text-xs text-gray-500">选择用于模拟的下注策略表</p>
            </div>

            <div class="mb-4">
              <div class="flex items-center mb-1">
                <label class="block text-sm font-medium text-gray-700 w-24">连续测试次数</label>
                <div class="flex-1">
                  <input 
                    v-model.number="continuousSimulationCount" 
                    type="number" 
                    min="1"
                    max="100"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                  <p class="mt-1 text-xs text-gray-500">设置连续执行多少轮测试，结果直接记录到历史中</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 模拟控制 -->
      <div class="flex justify-center space-x-4 mb-6">
        <button 
          @click="startSimulation(false)"
          class="px-5 py-3 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-xl font-bold shadow hover:from-blue-600 hover:to-blue-700 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
          :disabled="isSimulating || !isFormValid"
        >
          {{ isSimulating ? '模拟中...' : '开始模拟' }}
        </button>
        
        <button 
          @click="startSimulation(true)"
          class="px-5 py-3 bg-gradient-to-r from-green-500 to-green-600 text-white rounded-xl font-bold shadow hover:from-green-600 hover:to-green-700 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
          :disabled="isSimulating || !isFormValid"
        >
          {{ isSimulating ? '模拟中...' : `连续测试 ${continuousSimulationCount} 次` }}
        </button>
        
        <button 
          @click="resetForm"
          class="px-5 py-3 bg-gradient-to-r from-gray-400 to-gray-500 text-white rounded-xl font-bold shadow hover:from-gray-500 hover:to-gray-600 transition-all duration-200"
          :disabled="isSimulating"
        >
          重置参数
        </button>
      </div>
      
      <!-- 模拟进度 -->
      <div v-if="isSimulating" class="bg-white rounded-xl shadow-md p-6 mb-6">
        <h2 class="text-xl font-bold text-gray-800 mb-4">模拟进度</h2>
        
        <div v-if="isContinuousSimulation" class="mb-4">
          <div class="flex justify-between mb-1">
            <span class="text-sm text-gray-600">总体进度 ({{currentSimulationIndex}}/{{continuousSimulationCount}})</span>
            <span class="text-sm text-gray-600">{{Math.floor((currentSimulationIndex/continuousSimulationCount)*100)}}%</span>
          </div>
          <div class="w-full bg-gray-200 rounded-full h-2 mb-4">
            <div 
              class="bg-green-600 h-2 rounded-full transition-all duration-300" 
              :style="{ width: `${(currentSimulationIndex/continuousSimulationCount)*100}%` }"
            ></div>
          </div>
        </div>
        
        <div class="flex justify-between mb-1">
          <span class="text-sm text-gray-600">当前模拟</span>
          <span class="text-sm text-gray-600">{{simulationProgress}}%</span>
        </div>
        <div class="w-full bg-gray-200 rounded-full h-4 mb-2">
          <div 
            class="bg-blue-600 h-4 rounded-full transition-all duration-300" 
            :style="{ width: `${simulationProgress}%` }"
          ></div>
        </div>
        <p v-if="isContinuousSimulation" class="text-sm text-gray-600 mt-4">
          已完成: {{currentSimulationIndex}} / {{continuousSimulationCount}} 次模拟
        </p>
      </div>
      
      <!-- 模拟历史记录 -->
      <div v-if="simulationHistory.length > 0" class="bg-white rounded-xl shadow-md p-6">
        <h2 class="text-xl font-bold text-gray-800 mb-4">历史模拟</h2>
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">策略名称</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">总局数</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">盈利</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">主打方向</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时间</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="sim in simulationHistory" :key="sim.id" class="hover:bg-gray-50">
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ sim.id }}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ sim.strategy_name }}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ sim.total_rounds }}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm" :class="sim.net_profit > 0 ? 'text-green-600' : 'text-red-500'">
                  {{ sim.net_profit > 0 ? '+' : '' }}{{ sim.net_profit }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ sim.main_choice === 'player' ? '闲' : (sim.main_choice === 'banker' ? '庄' : '未确定') }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ sim.timestamp }}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  <button 
                    @click="viewResults(sim.id)"
                    class="text-blue-600 hover:text-blue-800 font-medium"
                  >
                    查看结果
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from '../logic/api'

export default {
  name: 'SimulationPage',
  data() {
    return {
      simulationParams: {
        strategy_name: '三反四看五跟测试',
        max_rounds: 1000,
        deck_seed: null,
        parameters: {
          observation_rounds: 6,
          strategy_table_id: null
        }
      },
      isSimulating: false,
      simulationProgress: 0,
      simulationHistory: [],
      simulationInterval: null,
      continuousSimulationCount: 10,
      isContinuousSimulation: false,
      currentSimulationIndex: 0,
      latestSimulationId: null,
      strategyTables: [],
      loadingStrategyTables: false,
      selectedStrategyTableId: null
    }
  },
  computed: {
    isFormValid() {
      return this.selectedStrategyTableId !== null && 
             this.simulationParams.strategy_name.trim() !== '' &&
             this.simulationParams.max_rounds > 0;
    }
  },
  mounted() {
    this.fetchSimulationHistory();
    this.fetchStrategyTables();
  },
  methods: {
    async fetchStrategyTables() {
      this.loadingStrategyTables = true;
      try {
        const data = await api.betStrategyTables.getAll();
        this.strategyTables = data;
        
        // 如果策略表为空，尝试创建一个默认表
        if (!data || data.length === 0) {
          console.log('没有找到策略表，尝试创建默认策略表');
          await this.createDefaultStrategyTable();
          // 重新获取
          const newData = await api.betStrategyTables.getAll();
          this.strategyTables = newData || [];
        }
        
        // 如果有默认策略表，自动选择它
        const defaultTable = this.strategyTables.find(table => table.is_default);
        if (defaultTable) {
          this.selectStrategyTable(defaultTable);
        } else if (this.strategyTables.length > 0) {
          // 否则选择第一个
          this.selectStrategyTable(this.strategyTables[0]);
        }
      } catch (error) {
        console.error('获取策略表异常', error);
      } finally {
        this.loadingStrategyTables = false;
      }
    },
    
    async createDefaultStrategyTable() {
      try {
        // 创建一个简单的默认策略表
        const defaultStrategyTable = {
          name: '默认策略表',
          description: '系统自动创建的默认策略表',
          strategy_content: '+1000:1000\n-1000:1100\n-1100:1300\n-1300:1700\n-1700:1000',
          is_default: true
        };
        
        console.log('正在创建默认策略表...');
        const result = await api.betStrategyTables.create(defaultStrategyTable);
        console.log('默认策略表创建结果:', result);
        return result;
      } catch (error) {
        console.error('创建默认策略表失败:', error);
        return null;
      }
    },
    
    selectStrategyTable(table) {
      this.selectedStrategyTableId = table.id;
      this.simulationParams.parameters.strategy_table_id = table.id;
    },
    
    async fetchSimulationHistory() {
      try {
        const data = await api.simulations.getAll();
        this.simulationHistory = data;
      } catch (error) {
        console.error('获取模拟历史失败', error);
      }
    },
    
    async startSimulation(continuous = false) {
      if (!this.isFormValid) {
        alert('请选择下注策略表并完成其他必填参数');
        return;
      }
      
      this.isSimulating = true;
      this.simulationProgress = 0;
      
      if (continuous) {
        this.isContinuousSimulation = true;
        this.currentSimulationIndex = 0;
        await this.runContinuousSimulations();
      } else {
        this.isContinuousSimulation = false;
        await this.runSingleSimulation(true);
      }
    },
    
    async runContinuousSimulations() {
      const totalRuns = this.continuousSimulationCount;
      
      for (let i = 0; i < totalRuns; i++) {
        if (!this.isSimulating) break; // 如果用户中止了过程
        
        this.currentSimulationIndex = i;
        await this.runSingleSimulation(false);
        
        // 最后一轮
        if (i === totalRuns - 1) {
          this.currentSimulationIndex = totalRuns;
          this.isSimulating = false;
          this.isContinuousSimulation = false;
          this.simulationProgress = 0;
          // 刷新历史记录
          await this.fetchSimulationHistory();
        }
      }
    },
    
    async runSingleSimulation(navigateToResult = false) {
      this.simulationProgress = 0;
      
      // 模拟进度动画
      this.simulationInterval = setInterval(() => {
        if (this.simulationProgress < 98) {
          this.simulationProgress += Math.floor(Math.random() * 5) + 1;
        }
      }, 300);
      
      try {
        // 每次模拟使用不同的种子
        if (this.isContinuousSimulation) {
          // 连续模拟时，使用范围更小的随机数作为种子
          // 确保不超过PostgreSQL整数字段限制（约21亿）
          this.simulationParams.deck_seed = Math.floor(Math.random() * 1000000) + this.currentSimulationIndex;
        }
        
        console.log('发送模拟请求，参数:', JSON.stringify(this.simulationParams));
        const result = await api.simulations.run(this.simulationParams);
        console.log('模拟结果:', result);
        
        clearInterval(this.simulationInterval);
        
        this.simulationProgress = 100;
        
        // 添加防护机制，确保result存在且包含simulation_id
        if (result && result.simulation_id) {
          this.latestSimulationId = result.simulation_id;
          
          if (!this.isContinuousSimulation) {
            // 刷新历史记录
            await this.fetchSimulationHistory();
            
            // 单次模拟时，等待后再导航到结果页
            if (navigateToResult) {
              setTimeout(() => {
                this.isSimulating = false;
                this.simulationProgress = 0;
                this.viewResults(result.simulation_id);
              }, 1000);
            }
          }
          
          return true;
        } else {
          // 如果result没有simulation_id，抛出错误
          console.error('服务器返回数据:', result);
          throw new Error("服务器返回数据格式不正确，缺少模拟ID");
        }
      } catch (error) {
        clearInterval(this.simulationInterval);
        this.isSimulating = false;
        console.error('模拟执行错误:', error);
        
        // 详细的错误信息
        if (error.response) {
          console.error('服务器响应:', error.response);
          console.error('状态码:', error.response.status);
          console.error('响应内容:', error.response.data);
        } else if (error.request) {
          console.error('请求信息:', error.request);
        }
        
        // 完整的错误信息
        let errorMsg = error.message || '未知错误';
        if (error.response) {
          // 服务器返回了错误状态码
          errorMsg = `服务器错误(${error.response.status}): ${error.response.data || errorMsg}`;
        } else if (error.request) {
          // 请求发送但没有收到响应
          errorMsg = '无法连接到服务器，请检查网络或服务器状态';
        }
        
        alert('模拟失败：' + errorMsg);
        return false;
      }
    },
    
    resetForm() {
      this.simulationParams = {
        strategy_name: '三反四看五跟测试',
        max_rounds: 1000,
        deck_seed: null,
        parameters: {
          observation_rounds: 6,
          strategy_table_id: this.selectedStrategyTableId
        }
      };
      this.continuousSimulationCount = 10;
    },
    
    viewResults(simulationId) {
      this.$router.push(`/simulation-result/${simulationId}`);
    }
  },
  beforeUnmount() {
    if (this.simulationInterval) {
      clearInterval(this.simulationInterval);
    }
  }
}
</script> 